import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  user: {},
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER: (state, user) => {
    state.user = user
    sessionStorage.setItem('user', JSON.stringify(user))
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
    sessionStorage.setItem('roles', JSON.stringify(roles))
  }
}

const actions = {
  authLogin ({ commit }, data) {
    commit('SET_TOKEN', data.access_token)
    commit('SET_USER', data)
    setToken(data.access_token)
  },
  login ({ commit }, code) {
    return new Promise((resolve, reject) => {
      const uidObj = JSON.parse(localStorage.getItem('uidObj')) || {}
      login({ code: code, uid: Object.values(uidObj).join() }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.access_token)
        commit('SET_USER', data.user_info)

        const uidObj = JSON.parse(localStorage.getItem('uidObj')) || {}
        const uidNew = {
          [data.user_info.id]: data.user_info.uid
        }
        Object.assign(uidObj, uidNew)
        localStorage.setItem('uidObj', JSON.stringify(uidObj))

        const roles = data.user_info.role
        if (typeof roles === 'object' && roles.constructor === Array) {
          commit('SET_ROLES', roles)
        } else {
          commit('SET_ROLES', roles.toString().split(''))
        }

        setToken(data.access_token)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  logout ({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_USER', {})
      commit('SET_ROLES', [])
      removeToken()
      // resetRouter()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
